package logic

import (
	"context"
	"encoding/json"
	"proto/models"
	"time"

	"proto/protorpc/internal/svc"
	"proto/protorpc/protorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *protorpc.ListRequest) (*protorpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var proto []models.Proto
	//缓存
	result, err := models.Rdb.Get("proto").Result()
	if err != nil {
		models.DB.Debug().Model(&models.Proto{}).Find(&proto)
		marshal, _ := json.Marshal(&proto)
		models.Rdb.Set("proto", marshal, time.Minute*60)
	} else {
		json.Unmarshal([]byte(result), &proto)
	}

	if err != nil {
		return nil, err
	}
	models.DB.Find(&proto)
	var allproto []*protorpc.List
	for _, m := range proto {
		list := protorpc.List{
			Id:    int64(m.ID),
			Name:  m.Name,
			Price: float32(m.Price),
			Stock: m.Stock,
			Img:   m.Img,
		}
		allproto = append(allproto, &list)
	}
	return &protorpc.ListResponse{
		List: allproto,
	}, nil
}
